import qrcode from './qrcode.js'
let ctx, canvas;

/**
   * 绘制图片
   * @param {object} options: width & height & views
   * @param {number} options.width: 宽度
   * @param {number} options.height: 高度
   * @param {array}  options.views: 绘制内容
   * */
export function makePoster(options) {
	return new Promise(async (resolve,reject)=>{
		try{
			if (!options) {
				return reject('缺少参数');
			}
			if(canvas === undefined){
				canvas = document.createElement('canvas');
				canvas.height = options.height;
				canvas.width = options.width;
			}
			if (ctx === undefined) {
				ctx = canvas.getContext("2d");
			}
			ctx.fillStyle = options.backgroundColor || 'rgba(0,0,0,0)';
			ctx.fillRect(0,0,options.width,options.height);
			// 根据z排序
			let views = options.views.sort((i,j)=>{
				return i.pos.z - j.pos.z;
			});
			for (let item of views) {
				switch(item.type){
					case 'image':
					await drawImage(item);
					break;
					case 'text':
					await drawText(item);
					break;
					case 'qrcode':
					await drawQRCode(item);
					break;
				}
			}
			return resolve({base64:canvas.toDataURL("image/png")});
		}catch(e){
			return reject(e);
		}
	})
}

/**
   * 生成图片
   * @param {object} obj: 图片对象
   * */
async function drawImage(obj) {
	try{
		let { src,pos } = obj;
		let { x,y,w,h,radius=0 } = pos;
		let img = await loadImage(src);
		// ctx.drawImage(img,x,y,w,h);
		
		ctx.beginPath();
		ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2);
		ctx.lineTo(w - radius + x, y);
		ctx.arc(w - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2);
		ctx.lineTo(w + x, h + y - radius);
		ctx.arc(w - radius + x, h - radius + y, radius, 0, Math.PI * 1 / 2);
		ctx.lineTo(radius + x, h + y);
		ctx.arc(radius + x, h - radius + y, radius, Math.PI * 1 / 2, Math.PI);
		ctx.lineTo(x, y + radius);
		// context.closePath();
		ctx.clip(); //裁剪
		ctx.stroke()
		ctx.drawImage(img,x,y,w,h)
		ctx.restore();
		
	}catch(e){
		console.error(e);
	}
}

/**
   * 生成文字
   * @param {object} obj: 文字对象
   * */
function drawText(obj) {
	try{
		let { content,line } = obj;
		let { fontSize,color,fontWeight } = obj.style;
		let { x,y,w,h } = obj.pos;
		
		let chr = content.toString().split('');
		const lineHeight = parseFloat(fontSize.split('px')[0] || 16) * 1.2;
		
		let temp = "";
		let row = [];
		let font = `normal small-caps ${fontWeight} ${fontSize} arial`;
		ctx.font = font;
		ctx.fillStyle = color || '#333333';
		ctx.textBaseline = "top";
		ctx.textAlign = 'left';
		for (let a = 0; a < chr.length; a++) {
			if (ctx.measureText(temp).width < w && ctx.measureText(temp + (chr[a])).width <= w) {
				temp += chr[a];
			}
			else {
				row.push(temp);
				temp = chr[a];
			}
		}
		row.push(temp);
				
		for (let b = 0; b < row.length; b++) {
			let str = row[b];
			if(line) {
				if(b > line-1){
					return
				}
				if(b === line -1){
					str = str.substring(0,str.length-1) + '...';
				}
			}
			ctx.fillText(str, x, y + lineHeight * b); //字体20，间隔24。类似行高
		}
	}catch(e){
		console.error(e);
	}
}

/**
   * 生成二维码
   * @param {object} obj: 二维码对象
   * */
async function drawQRCode(obj) {
	try{
		let { x,y,w,h } = obj.pos;
		let { content } = obj;
		let p = 0.07;// 白边比例
		let img = await makeQRCode(content);
		ctx.fillStyle = '#FFFFFF';
		ctx.fillRect(x,y,w,h);
		ctx.drawImage(img, x + w*p, y + h*p, w*(1-p*2), h*(1-p*2));
	}catch(e){
		console.error(e)
	}
}

/**
   * 图片加载异步改同步
   * @param {string} src: 图片链接
   * */
function loadImage(src){
	return new Promise((resolve,reject)=>{
		var img = new Image();
		img.src = src;
		img.onload = function(){
			resolve(img)
		}
	})
}

/**
   * 生成二维码异步改同步
   * @param {string} text: 二维码内容
   * */
function makeQRCode(text){
	return new Promise((resolve,reject)=>{
		const qrCode = new qrcode(null, {
			text: text, // 生成内容,
			width: 300,
			height: 300,
			correctLevel: 3,
			colorDark: '#000000',
			colorLight: '#ffffff'
		})
		let img = qrCode._oDrawing._elImage
		img.onload = function(){
			resolve(img)
		}
	})
}